package com.lalameow.smithing.listener;

import com.lalameow.common.exception.LaLaMeowException;
import com.lalameow.common.message.LaLaMeowMessage;
import com.lalameow.smithing.Smithing;
import com.lalameow.smithing.config.ConfigManager;
import com.lalameow.smithing.entity.EquimentEntity;
import com.lalameow.smithing.recipe.ForgeItem;
import com.lalameow.smithing.util.Constans;
import com.lalameow.smithing.util.VaildUtils;
import me.dpohvar.powernbt.api.NBTCompound;
import me.dpohvar.powernbt.api.NBTList;
import me.dpohvar.powernbt.api.NBTManager;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.Sound;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.inventory.FurnaceBurnEvent;
import org.bukkit.event.inventory.FurnaceSmeltEvent;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryType;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.AnvilInventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;

import java.util.HashMap;


/**
 * Created with IntelliJ IDEA.
 * 创建人: 陈刚
 * 日期: 2017/3/3
 * 时间: 13:08
 * 功能：请进行修改
 */
public class SmithingListener implements Listener {
    private HashMap<Integer, String> fuelItemMap = new HashMap<Integer, String>();
    private HashMap<Integer, Player> playerMap = new HashMap<Integer, Player>();
    @EventHandler
    public void onFurnaceBurn(FurnaceBurnEvent e) {
        Block block=e.getBlock();
        if(block!=null && (block.getType().equals(Material.FURNACE)|| block.getType().equals(Material.BURNING_FURNACE))){
            NBTCompound nbtCompound= NBTManager.nbtManager.read(block);
            ItemStack fuel=e.getFuel(); Player player=playerMap.get(block.hashCode());
            if(fuel==null || nbtCompound==null || player==null){
                return;
            }
            String blockName=nbtCompound.getString(Constans.NBTCUSTOMNAME);
            if(VaildUtils.vaildSmithBlock(blockName)){//判断是不是定义的锻造炉
                NBTList nbtList=nbtCompound.getList(Constans.NBTITEMS);//获取熔炉插槽的物品
                if(nbtList!=null && nbtList.size()>0){
                    boolean eqFlag=false;
                    boolean fuelFlag=false;
                    NBTCompound itemNBT=(NBTCompound)nbtList.get(0);
                    try{
                        if(itemNBT.getByte(Constans.NBTSLOT)==0){//判断强化装备
                            eqFlag= VaildUtils.vaildEqument(itemNBT);
                        }
                        if( fuel.getItemMeta()!=null){
                            fuelFlag= VaildUtils.vaildFuel(fuel);
                        }
                    }catch (LaLaMeowException ex){
                        Smithing.plugin.getLogger().info("锻造物品验证异常");
                    }
                    if(eqFlag && fuelFlag){
                        EquimentEntity equimentEntity= ConfigManager.equimentMap.get(ChatColor.stripColor(VaildUtils.readItemName(itemNBT)));
                        boolean passVail=false;
                        try {
                            passVail= VaildUtils.vailEqmentOper(equimentEntity,fuel,itemNBT);
                        } catch (LaLaMeowException e1) {
                            LaLaMeowMessage.sendError(playerMap.get(block.hashCode()),e1.getMessage());
                            LaLaMeowMessage.sendError(playerMap.get(block.hashCode()), ChatColor.DARK_RED + "锻造炉已经停止工作,请重新打开！");
                            Smithing.plugin.getLogger().info(e1.getMessage());
                            removePlayer(block.hashCode());
                            e.setCancelled(true);
                            return;
                        }
                        if(passVail){
                            addFuelItem(block.hashCode(), fuel.getItemMeta().getDisplayName());
                            e.setBurning(true);
                            e.setBurnTime(230);
                        }
                    }
                }
        }
    }

}
    @EventHandler
    public void onFurnaceSmelt(FurnaceSmeltEvent e) {
        ItemStack itemStack=e.getSource();
        Block block=e.getBlock();
        if(block!=null && (block.getType().equals(Material.FURNACE)|| block.getType().equals(Material.BURNING_FURNACE))) {
            NBTCompound nbtCompound = NBTManager.nbtManager.read(block);
            String blockName=nbtCompound.getString(Constans.NBTCUSTOMNAME);
            if(VaildUtils.vaildSmithBlock(blockName)){//判断是否为自定义路子
                ItemStack forgeItem= null;
                Player player=playerMap.get(block.hashCode());
                if(player==null){
                    e.setCancelled(true);
                    return;
                }
                try {
                    forgeItem = ForgeItem.forge(fuelItemMap.get(block.hashCode()), itemStack.clone(), player);
                    if(forgeItem!=null){
                        e.setResult(forgeItem);
                        player.playSound(player.getLocation(), Sound.BLOCK_ANVIL_USE, 1.0F, 1.0F);
                    }else{
                        LaLaMeowMessage.sendError(playerMap.get(block.hashCode()),"锻造炉出错了，请联系管理员");
                        Smithing.plugin.getLogger().info(playerMap.get(block.hashCode()).getName()+"锻造物品时出错了\n装备:"+itemStack.getItemMeta().getDisplayName()+"\n锻造石为："+fuelItemMap.get(block.hashCode()));
                        e.setCancelled(true);
                    }
                } catch (LaLaMeowException e1) {
                    LaLaMeowMessage.sendError(playerMap.get(block.hashCode()), e1.getMessage());
                    Smithing.plugin.getLogger().info(e1.getMessage());
                    e.setCancelled(true);
                }
                if(player.getOpenInventory()==null ||player.getOpenInventory().getType()!= InventoryType.FURNACE){
                    removePlayer(block.hashCode());
                }
                removeFuelItem(block.hashCode());
            }
        }
    }

    @EventHandler
    public  void onPlayerInteract(PlayerInteractEvent e) {
        if(e.getAction().equals(Action.RIGHT_CLICK_BLOCK) && e.hasBlock() ){
            Block block=e.getClickedBlock();
            if(block!=null && (block.getType().equals(Material.FURNACE)|| block.getType().equals(Material.BURNING_FURNACE))) {
                NBTCompound nbtCompound = NBTManager.nbtManager.read(block);
                String blockName=nbtCompound.getString(Constans.NBTCUSTOMNAME);
                short cookTime=nbtCompound.getShort(Constans.NBTCOOKTIME);
                if(ConfigManager.smithBlockConfig.getSmithBlockName().equals(blockName)){
                    Player player=e.getPlayer();
                    if(playerMap.containsKey(block.hashCode())){
                        Player blp=playerMap.get(block.hashCode());
                        if(!player.getName().equalsIgnoreCase(blp.getName()) && cookTime>0){
                            LaLaMeowMessage.sendError(player,"当前熔炉玩家:"+blp.getName()+" 正在使用！");
                            e.setCancelled(true);
                        }else{
                            removePlayer(block.hashCode());
                            addPlayer(block.hashCode(),player);
                        }
                    }else{
                        addPlayer(block.hashCode(), player);
                    }
                }
            }
        }
    }

     /**
     * 铁毡附魔修理物品名字不会变改变
     * @param event
     */
    @EventHandler
    public void openAnvil(InventoryClickEvent event){
            if(event.getInventory() instanceof AnvilInventory){
                AnvilInventory anvilInventory=(AnvilInventory)event.getInventory();
                if(anvilInventory.getItem(2)==null){
                    return;
                }
                ItemStack itemStack=anvilInventory.getItem(0);
                if(itemStack!=null&&event.getSlotType()== InventoryType.SlotType.RESULT&&event.getSlot()==2){
                    if(itemStack.getItemMeta()==null || itemStack.getItemMeta().getDisplayName()==null){
                        return;
                    }
                    ItemStack curItem=event.getCurrentItem();
                    ItemMeta itemMeta=curItem.getItemMeta();
                    itemMeta.setDisplayName(itemStack.getItemMeta().getDisplayName());
                    curItem.setItemMeta(itemMeta);
                    event.setCurrentItem(curItem);
            }
        }
    }
    private synchronized void addFuelItem(Integer hashcode,String fuelItem){
        fuelItemMap.put(hashcode, fuelItem);
    }
    private synchronized void removeFuelItem(Integer hashcode){
        fuelItemMap.remove(hashcode);
    }
    private synchronized void addPlayer(Integer hashcode,Player player){
        playerMap.put(hashcode, player);
    }
    private synchronized void removePlayer(Integer hashcode){
        playerMap.remove(hashcode);
    }


}
